var app = new Vue({
    el: '#auditPrice',
    data () {
        return {
            headerTitle: '审核价格',
            showType: 0, // 0 待审核商品列表，1 审核历史, 2 价格纠错
            marketName: '',
            changeMarketTitle: '', // 选择超市或修改超市
            market: { // 超市名和超市ID
                marketName: '',
                marketId: null,
            },
            toBeAuditedListData: null, // 待审核商品列表数据
            auditListHistoryData: null, // 审核历史列表数据
            currentPage: 1,
            totalPage: 2,
            pageSize: 12,
            pullUpLoad: false,
            pullUpLoadThreshold: 0,
            pullUpLoadNoMoreTxt: '没有更多了！',
            showPrice: null,
            imageSrc: '',
            btnDisabled: false,
            goodsPrice: '',
            params: { //商品纠错数据
                supermarketId: '',
                goodsSkuId: '',
                priceType: '请选择价格类型',
                startTime: '请选择开始时间',
                endTime: '请选择结束时间',
                price: '',
                file: '',
                correctType: ''
            },
            selectedLabel: '待审核',
            tabLabels: [
                {
                    label: '待审核'
                }, {
                    label: '已审核'
                }
            ],
            selectedValue: '未生效价格',
            tabValue: [
                {
                    label: '未生效价格'
                }, {
                    label: '已生效价格'
                }
            ],
            categoryId: null,
            categoryData: [],
            loop: false,
            autoPlay: false,
            showDots: false,
            slideOptions: {
                click: false,
                listenScroll: true,
                probeType: 3,
                directionLockThreshold: 0
            },
            affectedPriceData: null,
            marketKey: '', // 超市名搜索关键字
            marketData: null, // 超市搜索结果列表数据
            ineffectiveData: null,
            takeEffectData: null,
            taskDate: '',
            priceType: ''
        }
    },
    created() {
        let market = JSON.parse(localStorage.getItem('market'))
        if (market) {
            this.changeMarketTitle = '修改超市'
            this.market.marketName = market.marketName
            this.market.marketId = market.marketId
            this.params.supermarketId = market.marketId
        } else {
            this.changeMarketTitle = '选择超市'
        }
        this.getIneffectiveData()
    },
    watch: {
        marketKey (val) {
            if (val.length > 0) {
                this.pullUpLoad = true
                this.currentPage = 1
                this.getMarketData()
            } else {
                this.marketData = null
                this.pullUpLoad = false
            }
        }
    },
    computed: {
        initialIndex () {
            let index = 0
            index = this.findIndex(this.tabLabels, item => item.label === this.selectedLabel)
            return index
        },
        ineffectiveIndex () {
            let index = 0
            index = this.findIndex(this.tabValue, item => item.label === this.selectedValue)
            return index
        },
        scrollOptions () {
            return {
                pullUpLoad: this.pullUpLoadObj
            }
        },
        pullUpLoadObj: function() {
            return this.pullUpLoad ? {
                threshold: parseInt(this.pullUpLoadThreshold),
                txt: {
                    noMore: this.pullUpLoadNoMoreTxt
                }
            } : false
        }
    },
    methods: {
        // 返回
        goback () {
            if (this.showType === 0) {
                window.history.go(-1)
            } else if (this.showType === 1) {
                this.currentPage = 1
                this.pullUpLoad = false
                this.categoryId = null
                if (this.selectedValue === '未生效价格') {
                    this.getIneffectiveData()
                } else if (this.selectedValue === '已生效价格') {
                    this.getTakeEffectData()
                }
                this.headerTitle = '价格审核'
                this.showType = 0
            } else if (this.showType === 2) {
                this.currentPage = 1
                this.pullUpLoad = false
                this.getToBeAuditedListData()
                this.showType = 1
                if (this.priceType === 'WAIT_AUDIT') {
                    this.headerTitle = '未生效价格'
                } else if (this.priceType === 'AFFECTED') {
                    this.headerTitle = '已生效价格'
                }
            }
        },
        // 右侧选择超市弹窗弹出
        changeMarket () {
            this.marketKey = ''
            this.marketData = null
            const choiceMarket = this.$refs.choiceMarket
            choiceMarket.show()
        },
        // 右侧选择超市弹窗无限加载超市列表数据
        marketDataMore () {
            this.currentPage ++
            if(this.currentPage > this.totalPage){
                this.$refs.marketData.forceUpdate()
                return
            }
            this.getMarketData()
        },
        // 右侧选择超市弹窗获取超市列表数据
        getMarketData () {
            Axios.post('area/Supermarket/getSupermarketByKey.do', {
                key: this.marketKey,
                currentPage: this.currentPage,
                pageSize: this.pageSize
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.data
                    let reg = new RegExp(this.marketKey, 'g')
                    list.forEach(item => {
                        item.name = item.name.replace(reg, '<i>' + this.marketKey +'</i>')
                    })
                    if (this.currentPage === 1) {
                        this.marketData = list
                    } else {
                        this.marketData = this.marketData.concat(list)
                    }
                    this.totalPage = res.data.totalPage

                    if (this.currentPage >= this.totalPage) {
                        this.$refs.marketData.forceUpdate()
                    }
                }
            })
        },
        // 右侧选择超市弹窗选择超市
        choiceMarket (item) {
            let reg = new RegExp('<i>', 'g')
            let reg1 = new RegExp('</i>', 'g')
            item.name = item.name.replace(reg, '')
            item.name = item.name.replace(reg1, '')
            this.market.marketName = item.name
            this.market.marketId = item.supermarketId
            this.params.supermarketId = item.marketId
            localStorage.setItem("market", JSON.stringify(this.market))
            this.changeMarketTitle = '修改超市'
            const choiceMarket = this.$refs.choiceMarket
            choiceMarket.hide()
            this.currentPage = 1
            this.selectedValue = '未生效价格'
            this.pullUpLoad = false
            this.getIneffectiveData()
        },
        findIndex(ary, fn) {
            if (ary.findIndex) {
                return ary.findIndex(fn)
            }
            let index = -1
            ary.some(function (item, i, ary) {
                const ret = fn.call(this, item, i, ary)
                if (ret) {
                    index = i
                    return ret
                }
            })
            return index
        },
        // 未生效和已生效tab切换
        clickShowType0 (label) {
            this.selectedValue = label
        },
        // 未生效和已生效滑动切换
        changeTab (index) {
            this.currentPage = 1
            this.pullUpLoad = false
            if (index === 0) {
                this.$refs.ineffectiveData.scrollTo(0, 0, 200, 'linear')
                this.getIneffectiveData()
            } else if (index === 1) {
                this.$refs.takeEffectData.scrollTo(0, 0, 200, 'linear')
                this.getTakeEffectData()
            }
            this.selectedValue = this.tabValue[index].label
        },
        // 待审核和已审核tab切换
        clickHandler (label) {
            this.selectedLabel = label
        },
        // 待审核和已审核滑动切换
        changePage (index) {
            this.currentPage = 1
            this.pullUpLoad = false
            if (index === 0) {
                this.$refs.auditList.scrollTo(0, 0, 200, 'linear')
                this.getToBeAuditedListData()
            } else if (index === 1) {
                this.$refs.auditListHistory.scrollTo(0, 0, 200, 'linear')
                this.getauditListHistoryData()
            }
            this.selectedLabel = this.tabLabels[index].label
        },
        // 右侧筛选弹窗弹出
        screenPopup () {
            this.categoryData = []
            this.categoryIdArray = []
            Axios.post('goods/category/showAllCategory.do', {}).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data
                    list.forEach(h1 => {
                        let children = []
                        let data = {
                            text: h1.name,
                            child: children
                        }
                        h1.children.forEach(h2 => {
                            let h2Data = {
                                value: h2.categoryId,
                                text: h2.name
                            }
                            data.child.push(h2Data)
                        })
                        this.categoryData.push(data)
                    })
                    this.pullUpLoad = false
                }
            })
            const screenPopup = this.$refs.screenPopup
            screenPopup.show()
        },
        // 右侧筛选弹窗选择分类
        clickCategory (item) {
            const screenPopup = this.$refs.screenPopup
            screenPopup.hide()
            this.currentPage = 1
            this.pullUpLoad = false
            if (this.categoryId && this.categoryId === item.value) {
                this.categoryId = null
                if (this.selectedLabel === '待审核') {
                    this.getToBeAuditedListData()
                } else if (this.selectedLabel === '已审核') {
                    this.getauditListHistoryData()
                }
            } else {
                this.categoryId = item.value
                if (this.selectedLabel === '待审核') {
                    this.getToBeAuditedListData()
                } else if (this.selectedLabel === '已审核') {
                    this.getauditListHistoryData()
                }
            }
        },
        // 未生效价格列表无限加载
        ineffectiveMore () {
            this.currentPage ++
            if(this.currentPage > this.totalPage){
                this.$refs.ineffectiveData.forceUpdate()
                return
            }
            this.getIneffectiveData()
        },
        // 获取未生效价格列表数据
        getIneffectiveData () {
            Axios.post('correct/correct/getTotalQuantity.do', {
                supermarketId: this.market.marketId,
                currentPage: this.currentPage,
                pageSize: this.pageSize,
                priceType: 'WAIT_AUDIT'
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.data
                    list.forEach(item => {
                        item.taskDate = new Date(item.taskDate).Format('yy-MM-dd')
                    })
                    if (this.currentPage === 1) {
                        this.ineffectiveData = list
                    } else {
                        this.ineffectiveData = this.ineffectiveData.concat(list)
                    }
                    this.totalPage = res.data.totalPage
                    if (this.currentPage < this.totalPage) {
                        this.pullUpLoad = true
                    }
                } else {
                    this.toast = this.$createToast({
                        txt: res.errorMsg,
                        type: 'txt'
                    })
                    this.toast.show()
                    this.$refs.ineffectiveData.forceUpdate()
                }
            })
        },
        // 已生效价格列表无限加载
        takeEffectMore () {
            this.currentPage ++
            if(this.currentPage > this.totalPage){
                this.$refs.takeEffectData.forceUpdate()
                return
            }
            this.getTakeEffectData()
        },
        // 获取已生效价格列表数据
        getTakeEffectData () {
            Axios.post('correct/correct/getTotalQuantity.do', {
                supermarketId: this.market.marketId,
                currentPage: this.currentPage,
                pageSize: this.pageSize,
                priceType: 'AFFECTED'
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.data
                    list.forEach(item => {
                        item.taskDate = new Date(item.taskDate).Format('yy-MM-dd')
                    })
                    if (this.currentPage === 1) {
                        this.takeEffectData = list
                    } else {
                        this.takeEffectData = this.takeEffectData.concat(list)
                    }
                    this.totalPage = res.data.totalPage
                    if (this.currentPage < this.totalPage) {
                        this.pullUpLoad = true
                    }
                } else {
                    this.toast = this.$createToast({
                        txt: res.errorMsg,
                        type: 'txt'
                    })
                    this.toast.show()
                    this.$refs.takeEffectData.forceUpdate()
                }
            })
        },
        // 点击未生效或已生效列表跳转到待审核
        clickIneffectiveOrTakeEffect (item) {
            this.taskDate = item.taskDate
            this.currentPage = 1
            this.pullUpLoad = false
            this.selectedLabel = '待审核'
            if (this.selectedValue === '未生效价格') {
                this.priceType = 'WAIT_AUDIT'
                this.headerTitle = '未生效价格'
            } else if (this.selectedValue === '已生效价格') {
                this.priceType = 'AFFECTED'
                this.headerTitle = '已生效价格'
            }
            this.getToBeAuditedListData()
            this.showType = 1
        },
        // 获取更多待审核商品列表数据
        auditListMore () {
            this.currentPage ++
            if(this.currentPage > this.totalPage){
                this.$refs.auditList.forceUpdate()
                return
            }
            this.getToBeAuditedListData()
        },
        // 获取待审核商品列表数据
        getToBeAuditedListData () {
            Axios.post('correct/correct/taskGoodsSkuList.do', {
                supermarketId: this.market.marketId,
                currentPage: this.currentPage,
                pageSize: this.pageSize,
                taskDate: this.taskDate,
                priceType: this.priceType,
                categoryId: this.categoryId
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.data
                    this.marketName = res.data.supermarketName
                    list.forEach(item => {
                        item.price = item.price / 100
                        item.createTime = new Date(item.createTime).Format('yy/MM/dd')
                        item.spreadRate = item.spreadRate + '%'
                    })
                    if (this.currentPage === 1) {
                        this.toBeAuditedListData = list
                    } else {
                        this.toBeAuditedListData = this.toBeAuditedListData.concat(list)
                    }
                    this.totalPage = res.data.totalPage
                    if (this.currentPage < this.totalPage) {
                        this.pullUpLoad = true
                    }
                } else {
                    this.toast = this.$createToast({
                        txt: res.errorMsg,
                        type: 'txt'
                    })
                    this.toast.show()
                    this.$refs.auditList.forceUpdate()
                }
            })
        },
        // 已审核列表无限加载
        auditListHistoryMore () {
            this.currentPage ++
            if(this.currentPage > this.totalPage){
                this.$refs.auditListHistory.forceUpdate()
                return
            }
            this.getauditListHistoryData()
        },
        // 获取已审核列表数据
        getauditListHistoryData () {
            Axios.post('correct/correct/getAuditHistory.do', {
                currentPage: this.currentPage,
                pageSize: this.pageSize,
                categoryId: this.categoryId
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.data
                    list.forEach(item => {
                        item.price = item.price / 100
                        item.spreadRate = item.spreadRate + '%'
                        if (item.manualAuditStatus === 'AUDIT_FAIL_CORRECT') {
                            item.manualAuditStatus = '价格错误修改价格'
                        } else if (item.manualAuditStatus === 'AUDIT_SUCCESS') {
                            item.manualAuditStatus = '审核通过'
                        } else if (item.manualAuditStatus === 'AUDIT_FAIL_EXPIRED') {
                            item.manualAuditStatus = '价格错误过期'
                        }
                    })
                    if (this.currentPage === 1) {
                        this.auditListHistoryData = list
                    } else {
                        this.auditListHistoryData = this.auditListHistoryData.concat(list)
                    }
                    this.totalPage = res.data.totalPage
                    if (this.currentPage < this.totalPage) {
                        this.pullUpLoad = true
                    }
                } else {
                    this.toast = this.$createToast({
                        txt: res.errorMsg,
                        type: 'txt'
                    })
                    this.toast.show()
                    this.$refs.auditListHistory.forceUpdate()
                }
            })
        },
        // 待审核列表审核通过按钮
        auditPass (item) {
            Axios.post('correct/correct/taskAuditSuccess.do', {
                taskId: item.taskId,
                correctId: item.correctId
            }).then(res => {
                if (res.respCode === 'S') {
                    this.currentPage = 1
                    this.pullUpLoad = false
                    this.getToBeAuditedListData()
                } else {
                    this.toast = this.$createToast({
                        txt: res.errorMsg,
                        type: 'txt'
                    })
                    this.toast.show()
                }
            })
        },
        // 待审核列表价格错误按钮
        priceError (item) {
            this.$createDialog({
                type: 'confirm',
                showClose: true,
                title: '价格错误',
                content: '请更改价格信息！',
                confirmBtn: {
                    text: '修改价格',
                    active: true,
                    disabled: false,
                    href: 'javascript:;'
                },
                cancelBtn: {
                    text: '暂无价格',
                    active: false,
                    disabled: false,
                    href: 'javascript:;'
                },
                onConfirm: () => {
                    this.priceCorrection(item)
                },
                onCancel: () => {
                    this.noPrice(item)
                },
                onClose: () => {}
            }).show()
        },
        // 价格错误弹窗点击暂无价格
        noPrice (item) {
            Axios.post('correct/correct/noTimePrice.do', {
                correctId: item.correctId,
                taskId: item.taskId,
                goodsSkuId: item.goodsSkuId,
                supermarketId: this.market.marketId
            }).then(res => {
                if (res.respCode === 'S') {
                    this.currentPage = 1
                    this.pullUpLoad = false
                    this.getToBeAuditedListData()
                } else {
                    this.$createToast({
                        type: 'txt',
                        time: 1500,
                        txt: res.errorMsg
                    }).show()
                }
            })
        },
        // 价格错误弹窗点击修改价格
        priceCorrection (item) {
            Axios.post('correct/correct/taskAuditPriceError.do', {
                correctId: item.correctId,
                taskId: item.taskId,
                goodsSkuId: item.goodsSkuId,
                supermarketId: item.supermarketId
            }).then(res => {
                if (res.respCode === 'S') {
                    this.params = {
                        supermarketId: item.supermarketId,
                        goodsSkuId: res.data.goodsSkuId,
                        priceType: '请选择价格类型',
                        startTime: '请选择开始时间',
                        endTime: '请选择结束时间',
                        price: '',
                        file: '',
                        correctType: res.data.correctType,
                        correctId: res.data.correctId
                    }
                    this.showType = 2
                    this.headerTitle = '价格纠错'
                } else {
                    this.$createToast({
                        type: 'txt',
                        time: 1500,
                        txt: res.errorMsg
                    }).show()
                }
            })
        },
        // 选择价格类型
        choicePriceType () {
            this.$createActionSheet({
                data: [
                    {
                        content: '正常价'
                    },
                    {
                        content: '促销价'
                    },
                    {
                        content: '处理价'
                    },
                    {
                        content: '会员价'
                    }
                ],
                onSelect: (item, index) => {
                    this.params.priceType = item.content
                },
                onCancel: () => {
                    
                }
            }).show()
        },
        // 开始时间和结束时间弹窗弹出
        choiceStartAndEndTime () {
            this.startAndEndTime()
            this.startAndEndTimePicker.show()
        },
        // 开始时间和结束时间弹窗初始化
        startAndEndTime () {
            let dateSegmentData = [
                {
                    is: 'cube-date-picker',
                    title: '开始时间',
                    min: new Date(),
                    max: new Date(2030, 12, 31, 23, 59),
                    columnCount: 5
                },
                {
                    is: 'cube-date-picker',
                    title: '结束时间',
                    min: new Date(),
                    max: new Date(2030, 12, 31, 23, 59),
                    columnCount: 5
                }
            ]
            this.startAndEndTimePicker = this.$createSegmentPicker({
                data: dateSegmentData,
                onSelect: (selectedDates, selectedVals, selectedTexts) => {
                    let startTime = selectedTexts[0]
                    let endTime = selectedTexts[1]
                    this.params.startTime = startTime[0] + '-' + startTime[1] + '-' + startTime[2] + ' ' + startTime[3] + ':' + startTime[4]
                    this.params.endTime = endTime[0] + '-' + endTime[1] + '-' + endTime[2] + ' ' + endTime[3] + ':' + endTime[4]
                },
                onNext: (i, selectedDate, selectedValue, selectedText) => {
                    dateSegmentData[1].min = selectedDate
                    if (i === 0) {
                        this.startAndEndTimePicker.$updateProps({
                            data: dateSegmentData
                        })
                    }
                }
            })
        },
        // 图片预览
        showImage() {
            let self = this
            let inputDOM = this.$refs.uploadFile;
            // 通过DOM取文件数据
            this.params.file = inputDOM.files[0];
            var reader = new FileReader();
            reader.onload = function (evt) {
                var srcString = evt.target.result;
                //安卓获取的base64数据无信息头，加之
                if (srcString.substring(5, 10) != "image") {
                    srcString = srcString.replace(/(.{5})/, "$1image/jpeg;");
                }
                self.imageSrc = srcString;
            }
            if (self.params.file) {
                reader.readAsDataURL(self.params.file);
            }
        },
        // 验证数据是否合法
        checkParam() {
            let data = this.params
            for (let i in data) {
                if (i === 'priceType') {
                    if (data[i] === '请选择价格类型' || data[i] === '') {
                        this.toast = this.$createToast({
                            txt: '请填写所有项',
                            type: 'txt'
                        })
                        this.toast.show()
                        return false
                    }
                } else if (i === 'startTime') {
                    if (data[i] === '请选择开始时间' || data[i] === '') {
                        this.toast = this.$createToast({
                            txt: '请填写所有项',
                            type: 'txt'
                        })
                        this.toast.show()
                        return false
                    }
                } else if (i === 'endTime') {
                    if (data[i] === '请选择结束时间' || data[i] === '') {
                        this.toast = this.$createToast({
                            txt: '请填写所有项',
                            type: 'txt'
                        })
                        this.toast.show()
                        return false
                    }
                } else if (i === "file") {

                } else {
                    if (data[i] === '') {
                        this.toast = this.$createToast({
                            txt: '请填写所有项',
                            type: 'txt'
                        })
                        this.toast.show()
                        return false
                    }
                }
            }
            return true
        },
        submit () {
            if (this.goodsPrice == this.showPrice) {
                this.$createDialog({
                    type: 'alert',
                    showClose: true,
                    title: '温馨提示',
                    content: '该商品已存在此错误价格记录，请重新填写正确的价格！',
                    onClose: () => {
                        this.showType = this.oldShowType
                    },
                }).show()
                return
            }
            let data = this.params
            this.btnDisabled = true

            data.price = Math.round(this.showPrice * 100)
            let param = new FormData()
            if (this.checkParam()) {
                for (let i in data) {
                    if (i === 'priceType') {
                        if (data[i] === '正常价') {
                            param.append(i, 'NORMAL')
                        } else if (data[i] === '促销价') {
                            param.append(i, 'PROMOTION')
                        } else if (data[i] === '处理价') {
                            param.append(i, 'DEAL')
                        } else if (data[i] === '会员价') {
                            param.append(i, 'MEMBER')
                        }
                    } else {
                        param.append(i, data[i])
                    }
                }
            } else {
                this.btnDisabled = false
                return
            }
            Axios.post('correct/correct/updatePriceByApp.do', param).then(res => {
                if (res.respCode === 'S') {
                    this.toast = this.$createToast({
                        txt: res.data,
                        type: 'txt'
                    })
                    this.toast.show()
                    this.selectedLabel = '待审核'
                    this.getToBeAuditedListData()
                    this.showType = 1
                    this.showPrice = null
                    this.params = {
                        supermarketId: '',
                        goodsSkuId: '',
                        priceType: '请选择价格类型',
                        startTime: '请选择开始时间',
                        endTime: '请选择结束时间',
                        price: '',
                        file: '',
                        correctType: ''
                    }
                    this.btnDisabled = false
                } else {
                    this.toast = this.$createToast({
                        txt: res.errorMsg,
                        type: 'txt'
                    })
                    this.toast.show()
                }
            }).catch(err => {
                console.error(err)
            })
        }
    }
})